package vh.android.multiconnector.quiz;

import vh.android.multiconnector.quiz.ui.dialogs.CloseGameDialogFragment;
import vh.android.multiconnector.quiz.ui.dialogs.StartGameDialogFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class GameAdminActivity extends FragmentActivity implements
		OnClickListener {

	private BroadcastReceiver mReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game_admin);

		Button btnClose = (Button) findViewById(R.id.btnCloseGame);
		Button btnStartGame = (Button) findViewById(R.id.btnStartGame);
		btnClose.setOnClickListener(this);
		btnStartGame.setOnClickListener(this);
	}

	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter(
				CloseGameDialogFragment.INTENT_ACTION_GAME_DIALOG);
		mReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				if (intent.hasExtra("close")) {
					// TODO close game
					finish();
				} else {
					// TODO start game
					finish();
				}
			}
		};
		LocalBroadcastManager.getInstance(getApplicationContext())
				.registerReceiver(mReceiver, filter);
	}

	@Override
	protected void onStop() {
		super.onStop();
		LocalBroadcastManager.getInstance(getApplicationContext())
				.unregisterReceiver(mReceiver);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnStartGame:
			// TODO send command to channel
			DialogFragment f = new StartGameDialogFragment();
			f.show(getSupportFragmentManager(), "start-game");
			break;
		case R.id.btnCloseGame:
			// TODO leave channel
			DialogFragment f1 = new CloseGameDialogFragment();
			f1.show(getSupportFragmentManager(), "close-game");
			break;

		default:
			break;
		}
	}
}
